package de.unibremen.mum.app.whatscool.camera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

public class TakePictureActivity extends FragmentActivity {

	private static final String LOG_TAG = TakePictureActivity.class.getSimpleName();

	private boolean done = true;
	private File sdDir;

	protected static final String PHOTO_TAKEN = "photo_taken";

	@Override
	public void onCreate(Bundle savedInstanceState) {

		try {
			super.onCreate(savedInstanceState);
			if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
				File root = new File(Environment.getExternalStorageDirectory() + File.separator + "images"
						+ File.separator);
				root.mkdirs();
				sdDir = new File(root, this.randomFilename());
				Log.d(LOG_TAG, "Creating image storage file: " + sdDir.getPath());
				startCameraActivity();
			} else {
				finish();
			}

		} catch (Exception e) {
			finish();
		}

	}

	public String randomFilename() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	/*
	 * By default, the picture taken will be returned as a thumbnail, available
	 * as a raw bitmap within the data extra within the returned Intent. To
	 * obtain a full image, you must specify a target file in which to store it,
	 * encoded as a URI passed in using the MediaStore.EXTRA_OUTPUT extra in the
	 * launch Intent
	 */
	protected void startCameraActivity() {
		Uri outputFileUri = Uri.fromFile(sdDir);
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		generateThumbnail(sdDir.getPath());
		Intent intent = new Intent();
		intent.putExtra("uri", sdDir.getPath());
		setResult(42, intent);
		finish();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		if (savedInstanceState.getBoolean(TakePictureActivity.PHOTO_TAKEN)) {
			done = true;
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean(TakePictureActivity.PHOTO_TAKEN, done);
	}

	private boolean generateThumbnail(String imageURI) {
		// Declare
		FileInputStream inStream = null;
		FileOutputStream outStream = null;

		try {
			// Load the bitmap from file
			inStream = new FileInputStream(imageURI);

			// Scale the bitmap by 10x
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 10;
			Bitmap scaledImage = BitmapFactory.decodeStream(inStream, null, options);

			// Save the scaled bitmap
			File thumbnail = new File(imageURI + "_thumbnail");
			if (!thumbnail.exists()) {
				thumbnail.createNewFile();
			}
			outStream = new FileOutputStream(thumbnail);
			scaledImage.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.close();

			// Recycle the bitmaps to immediately free memory
			scaledImage.recycle();
			scaledImage = null;

			return true;

		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// Clean-up if we failed on save
			if (outStream != null) {
				try {
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// Failed
		return false;
	}
}
